package com.imooc.miaosha.rabbitmq;

import com.imooc.miaosha.constant.MqConstant;
import com.imooc.miaosha.domian.MiaoShaOrder;
import com.imooc.miaosha.domian.User;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.MiaoShaService;
import com.imooc.miaosha.service.OrderService;
import com.imooc.miaosha.util.TypeConversionUtils;
import com.imooc.miaosha.vo.GoodsVO;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 模块描述: <br>
 * (消费者)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/24 13:18
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
public class MqReceiver {

    @RabbitListener(queues = MqConstant.QUEUE)
    public void receiver(String msg) {
        System.out.println(msg);
    }


    @RabbitListener(queues = MqConstant.TOPIC_QUEUE_1)
    public void topicReceiver1(String msg) {
        System.out.println("queue1:" + msg);
    }

    @RabbitListener(queues = MqConstant.TOPIC_QUEUE_2)
    public void topicReceiver2(String msg) {
        System.out.println("queue1:" + msg);
    }


    @RabbitListener(queues = MqConstant.HEADERS_QUEUE)
    public void headersReceiver2(byte[] msg) {
        System.out.println("headers_queue:" + new String(msg));
    }

    /**
     * 监听秒杀队列
     *
     * @param msg
     */
    @RabbitListener(queues = MqConstant.MIAOSHA_QUEUE)
    public void miaoshaReceiver(String msg) {
        MiaoshaMessage mm = TypeConversionUtils.stringToBean(msg, MiaoshaMessage.class);
        User user = mm.getUser();
        long goodsId = mm.getGoodsId();
        GoodsVO goods = goodsService.getGoodsVoByGoodsId(goodsId);
        Integer stockCount = goods.getStockCount();
        if (stockCount <= 0) {
            return;
        }
        // 查询是否抢购过了
        MiaoShaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
        if (order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        miaoShaService.miaoSha(user, goods);
    }

    @Autowired
    private MiaoShaService miaoShaService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;
}
